# -*- coding: utf-8 -*-
"""
管理员用户管理模块
包含用户的增删改查、批量操作等功能
@api-version: 1.0.0
REF: API-ADMIN-001~007
"""

from flask import request, g
from marshmallow import ValidationError
from sqlalchemy import or_
from backend.models.user import User
from backend.models.session import UserSession
from backend.schemas.user_schemas import UserCreateSchema, AdminUserUpdateSchema, PasswordResetSchema
from backend.utils.response import success_response, error_response, validation_error_response, not_found_response
from backend.utils.api_response import ApiResponse
from backend.utils.auth import admin_required, login_required
from backend.utils.pagination import paginate_query
from backend.models import db
from . import admin_bp


@admin_bp.route('/admin/users', methods=['GET'])
@admin_required
def get_users():
    """获取用户列表
    REF: API-ADMIN-001
    """
    try:
        # 获取查询参数
        search = request.args.get('search', '').strip()
        role = request.args.get('role', '').strip()
        status = request.args.get('status', type=int)
        
        # 构建查询
        query = User.query
        
        # 搜索条件
        if search:
            query = query.filter(
                or_(
                    User.username.like(f'%{search}%'),
                    User.email.like(f'%{search}%'),
                    User.real_name.like(f'%{search}%')
                )
            )
        
        # 角色筛选
        if role and role in ['admin', 'user']:
            query = query.filter(User.role == role)
        
        # 状态筛选
        if status is not None and status in [0, 1]:
            query = query.filter(User.status == status)
        
        # 排序
        query = query.order_by(User.created_at.desc())
        
        # 分页
        pagination_data = paginate_query(query)
        
        # 转换数据格式
        users_data = [user.to_dict() for user in pagination_data['items']]
        pagination_data['items'] = users_data
        
        return success_response(
            data=pagination_data,
            message='获取用户列表成功'
        )
        
    except Exception as e:
        return error_response('获取用户列表失败', 500)


@admin_bp.route('/admin/users', methods=['POST'])
@admin_required
def create_user():
    """创建用户
    REF: API-ADMIN-002
    """
    try:
        # 数据验证
        schema = UserCreateSchema()
        data = schema.load(request.get_json() or {})
        
        # 检查邮箱唯一性
        if User.query.filter_by(email=data['email']).first():
            return error_response('邮箱已被使用', 400)
        
        # 检查昵称唯一性
        if User.query.filter_by(nickname=data['nickname']).first():
            return error_response('昵称已被使用', 400)
        
        # 创建用户
        user = User(
            email=data['email'],
            nickname=data['nickname'],
            password=data['password'],
            role=data.get('role', 'user'),
            real_name=data.get('real_name'),
            phone=data.get('phone')
        )
        
        db.session.add(user)
        db.session.commit()
        
        return success_response(
            data={
                'userId': user.id,
                'nickname': user.nickname
            },
            message='用户创建成功'
        )
        
    except ValidationError as e:
        return validation_error_response(e.messages)
    except Exception as e:
        return error_response('用户创建失败', 500)


@admin_bp.route('/admin/users/<int:user_id>', methods=['GET'])
@admin_required
def get_user(user_id):
    """获取用户详情
    REF: API-ADMIN-003
    """
    try:
        user = User.query.get(user_id)
        if not user:
            return not_found_response('用户不存在')
        
        return success_response(
            data=user.to_dict(),
            message='获取用户详情成功'
        )
        
    except Exception as e:
        return error_response('获取用户详情失败', 500)


@admin_bp.route('/admin/users/<int:user_id>', methods=['PUT'])
@admin_required
def update_user(user_id):
    """更新用户信息
    REF: API-ADMIN-004
    """
    try:
        user = User.query.get(user_id)
        if not user:
            return not_found_response('用户不存在')
        
        # 数据验证
        schema = AdminUserUpdateSchema()
        data = schema.load(request.get_json() or {})
        
        # 检查邮箱唯一性（排除当前用户）
        if 'email' in data:
            existing_user = User.query.filter(
                User.email == data['email'],
                User.id != user_id
            ).first()
            if existing_user:
                return error_response('邮箱已被使用', 400)
        
        # 检查昵称唯一性（排除当前用户）
        if 'nickname' in data:
            existing_user = User.query.filter(
                User.nickname == data['nickname'],
                User.id != user_id
            ).first()
            if existing_user:
                return error_response('昵称已被使用', 400)
        
        # 更新用户信息
        for key, value in data.items():
            if hasattr(user, key):
                setattr(user, key, value)
        
        db.session.commit()
        
        return success_response(
            data=user.to_dict(),
            message='用户信息更新成功'
        )
        
    except ValidationError as e:
        return validation_error_response(e.messages)
    except Exception as e:
        return error_response('用户信息更新失败', 500)


@admin_bp.route('/admin/users/<int:user_id>', methods=['DELETE'])
@admin_required
def delete_user(user_id):
    """删除用户
    REF: API-ADMIN-005
    """
    try:
        user = User.query.get(user_id)
        if not user:
            return not_found_response('用户不存在')
        
        # 不能删除自己
        if user.id == g.current_user.id:
            return error_response('不能删除自己', 400)
        
        # 删除用户的所有会话
        UserSession.query.filter_by(user_id=user.id).delete()
        
        # 删除用户
        db.session.delete(user)
        db.session.commit()
        
        return success_response(
            data={'deleted_user_id': user_id},
            message='用户删除成功'
        )
        
    except Exception as e:
        return error_response('用户删除失败', 500)


@admin_bp.route('/admin/users/<int:user_id>/reset-password', methods=['POST'])
@admin_required
def reset_user_password(user_id):
    """重置用户密码
    REF: API-ADMIN-006
    """
    try:
        user = User.query.get(user_id)
        if not user:
            return not_found_response('用户不存在')
        
        # 数据验证
        schema = PasswordResetSchema()
        data = schema.load(request.get_json() or {})
        
        # 更新密码
        user.password = data['new_password']
        db.session.commit()
        
        return success_response(
            data={'user_id': user_id},
            message='密码重置成功'
        )
        
    except ValidationError as e:
        return validation_error_response(e.messages)
    except Exception as e:
        return error_response('密码重置失败', 500)


@admin_bp.route('/users/<int:user_id>/upload-permission', methods=['PUT'])
@login_required
@admin_required
def update_user_upload_permission(user_id):
    """更新用户文件上传权限
    REF: API-ADMIN-008
    """
    try:
        user = User.query.get_or_404(user_id)
        data = request.get_json() or {}
        
        can_upload_files = data.get('canUploadFiles')
        if can_upload_files is None:
            return ApiResponse.error("canUploadFiles参数不能为空", code=400).to_response()
        
        # 更新上传权限
        user.can_upload_files = bool(can_upload_files)
        db.session.commit()
        
        return ApiResponse.success({
            'userId': user.id,
            'canUploadFiles': user.can_upload_files,
            'message': f"用户上传权限已{'开启' if user.can_upload_files else '关闭'}"
        }).to_response()
        
    except Exception as e:
        db.session.rollback()
        return ApiResponse.error(f"更新上传权限失败: {str(e)}", code=500).to_response()


@admin_bp.route('/users/batch-upload-permission', methods=['PUT'])
@login_required
@admin_required
def batch_update_upload_permission():
    """批量更新用户文件上传权限
    REF: API-ADMIN-009
    """
    try:
        data = request.get_json() or {}
        user_ids = data.get('userIds', [])
        can_upload_files = data.get('canUploadFiles')
        
        if not user_ids:
            return ApiResponse.error("用户ID列表不能为空", code=400).to_response()
        
        if can_upload_files is None:
            return ApiResponse.error("canUploadFiles参数不能为空", code=400).to_response()
        
        # 批量更新
        updated_count = User.query.filter(User.id.in_(user_ids)).update(
            {User.can_upload_files: bool(can_upload_files)},
            synchronize_session=False
        )
        
        db.session.commit()
        
        return ApiResponse.success({
            'updatedCount': updated_count,
            'canUploadFiles': bool(can_upload_files),
            'message': f"已{'开启' if can_upload_files else '关闭'}{updated_count}个用户的上传权限"
        }).to_response()
        
    except Exception as e:
        db.session.rollback()
        return ApiResponse.error(f"批量更新上传权限失败: {str(e)}", code=500).to_response()


@admin_bp.route('/admin/users/batch', methods=['DELETE'])
@admin_required
def batch_delete_users():
    """批量删除用户
    REF: API-ADMIN-007
    """
    try:
        data = request.get_json() or {}
        user_ids = data.get('userIds', [])
        
        if not user_ids or not isinstance(user_ids, list):
            return error_response('用户ID列表不能为空', 400)
        
        # 检查是否包含当前用户
        if g.current_user.id in user_ids:
            return error_response('不能删除自己', 400)
        
        # 查找要删除的用户
        users = User.query.filter(User.id.in_(user_ids)).all()
        if not users:
            return error_response('没有找到要删除的用户', 404)
        
        deleted_count = 0
        for user in users:
            # 删除用户的所有会话
            UserSession.query.filter_by(user_id=user.id).delete()
            # 删除用户
            db.session.delete(user)
            deleted_count += 1
        
        db.session.commit()
        
        return success_response(
            data={'deletedCount': deleted_count},
            message=f'成功删除{deleted_count}个用户'
        )
        
    except Exception as e:
        return error_response('批量删除用户失败', 500)